import React, { useEffect } from "react";
import styles from "./PostListPage.module.css";
import { List, Typography } from "antd";
import Post, { Post_dao } from "./component/Post";
import PostNew from "./component/PostNew";
import { History } from "history";
import { useDispatch, useSelector } from "react-redux";
import { postList_a, postNew, PostStatus } from "./slice/postSlice";

interface Props {
    history: History;
}
/**
 * 帖子列表
 * */
const PostListPage = (props: Props) => {
    const { history } = props;
    const dispatch = useDispatch();
    const posts: Post_dao[] = useSelector((state: any) => {
        return state.posts.list;
    });
    const status: PostStatus = useSelector((state: any) => {
        return state.posts.status;
    });
    // const message: string | null = useSelector((state: any) => {
    //     return state.posts.message;
    // });

    useEffect(() => {
        const updateData = () => {
            dispatch(postList_a());
        };

        updateData();
    }, [posts, dispatch]);

    const onSave = (post: any) => {
        dispatch(postNew(post));
    };
    const onDetail = (post: any) => {
        const path = `/post/${post.id}`;
        history.push(path, post);
    };

    return (
        <div className={styles.main}>
            <Typography.Title level={3}>帖子列表</Typography.Title>
            <PostNew onSave={onSave} />
            <List
                loading={status === PostStatus.loading}
                dataSource={posts}
                renderItem={(item) => (
                    <List.Item>
                        <Post key={item.id} data={item} onDetail={onDetail} />
                    </List.Item>
                )}
                grid={{
                    gutter: 16,
                    column: 1,
                }}
            />
        </div>
    );
};

export default PostListPage;
